from bs4 import BeautifulSoup
import json
from bs4 import Tag
import sys  # 新增导入

def create_html_from_json(json_file, output_html, template_file):
    # 读取模板文件获取样式
    try:
        with open(template_file, 'r', encoding='utf-8') as f:
            template_soup = BeautifulSoup(f, 'html.parser')
    except FileNotFoundError:
        print(f"错误：模板文件 {template_file} 不存在")
        return
    
    # 获取模板中的样式元素
    style_elements = template_soup.find_all(style=True)
    
    # 读取JSON数据
    try:
        with open(json_file, 'r', encoding='utf-8') as f:
            articles = json.load(f)
    except FileNotFoundError:
        print(f"错误：文件 {json_file} 不存在")
        return
    
    # 创建基础HTML结构
    html_template = """
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">

    </head>
    <body>
    </body>
    </html>
    """
    soup = BeautifulSoup(html_template, 'html.parser')
    body = soup.find('body')
    
    # 为每篇文章创建section并应用样式
    for i, article in enumerate(articles, 1):
        section = soup.new_tag('section')
        
        # 应用section样式
        template_section = template_soup.find('section')
        # 检查template_section是否为Tag对象，避免NavigableString类型导致的错误
        if isinstance(template_section, Tag) and template_section.has_attr('style'):
            section['style'] = template_section['style']
        
        # 添加h1标签（序号）
        h1 = soup.new_tag('h1')
        template_h1 = template_soup.find('h1')
        if template_h1 and template_h1.has_attr('style'):
            h1['style'] = template_h1['style']
        span = soup.new_tag('span')
        span.string = f"{i:02d}"
        h1.append(span)
        section.append(h1)
        
        # 添加h2标签（标题）
        h2 = soup.new_tag('h2')
        template_h2 = template_soup.find('h2')
        if template_h2 and template_h2.has_attr('style'):
            h2['style'] = template_h2['style']
        span = soup.new_tag('span')
        span.string = article['title']
        h2.append(span)
        section.append(h2)
        
        # 添加p标签（内容）
        p = soup.new_tag('p')
        template_p = template_soup.find('p')
        if template_p and template_p.has_attr('style'):
            p['style'] = template_p['style']
        span = soup.new_tag('span')
        span.string = article['content']
        p.append(span)
        section.append(p)
        
        # 添加a标签（链接）
        a = soup.new_tag('a', href=article['link'])
        template_a = template_soup.find('a')
        if template_a and template_a.has_attr('style'):
            a['style'] = template_a['style']
        span = soup.new_tag('span')
        span.string = "原文链接"
        a.append(span)
        section.append(a)
        
        body.append(section)
    
    # 保存HTML文件
    with open(output_html, 'w', encoding='utf-8') as f:
        f.write(soup.prettify())

if __name__ == '__main__':
    # 检查命令行参数
    if len(sys.argv) > 1:
        template_num = sys.argv[1].zfill(2)  # 确保两位数格式
        template_path = rf'c:\Users\lenovo\Desktop\html2inline\template{template_num}.html'
    else:
        template_path = r'c:\Users\lenovo\Desktop\html2inline\template01.html'  # 默认模板
    
    json_path = r'c:\Users\lenovo\Desktop\html2inline\output.json'
    html_path = r'c:\Users\lenovo\Desktop\html2inline\articles.html'
    create_html_from_json(json_path, html_path, template_path)